/*
 * Copyright (C) 2011 by ayoung <ayoung.p@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.peaceb.ruletherain;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

/**
 * Add location by user
 */
public class AddLocationActivity extends Activity implements OnClickListener, OnEditorActionListener {
    private static final int PROGRESS_ID_SAVE = 0;
    
    private RuleTheRainApplication mApplication;
    private NetworkHandler         mHandler;
    private EditText               mEditCity;
    private RelativeLayout         mCityLayout;
    private ProgressBar            mQueryProgress;
    private TextView               mCityName;
    private ImageView              mIcon;
    private TextView               mCondition;
    private TextView               mCode;
    
    private Button                 mButtonQuery;
    private Button                 mButtonAdd;
    
    private WeatherInfo            mWeatherInfo;
    private Geocoder               mGeocoder;
    
    private ProgressDialog         mProgress;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_location);

        int height = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight();
        View adView = findViewById(R.id.ad);
        adView.setMinimumHeight((int)(height / 10));
        
        mEditCity      = (EditText)findViewById(R.id.input_city);
        mEditCity.setOnEditorActionListener(this);
        
        mCityLayout    = (RelativeLayout)findViewById(R.id.city_layout);
        mQueryProgress = (ProgressBar)findViewById(R.id.progress);
        mCityName      = (TextView)findViewById(R.id.city_name);
        mIcon          = (ImageView)findViewById(R.id.wether_icon);
        mCondition     = (TextView)findViewById(R.id.condition);
        mCode          = (TextView)findViewById(R.id.gps_value);
        
        mApplication   = (RuleTheRainApplication)getApplication();
        mHandler       = new NetworkHandler();
        mGeocoder      = new Geocoder(this);
        
        mButtonQuery   = (Button)findViewById(R.id.query);
        mButtonAdd     = (Button)findViewById(R.id.add);
        mButtonQuery.setOnClickListener(this);
        mButtonAdd.setOnClickListener(this);
        
        mWeatherInfo = new WeatherInfo();
        enableAdd(false);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if (mApplication.isDatabaseChanged()) {
            Util.showToast(this, R.string.reload_database);
            mApplication.loadCityList();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.query:
                query();
                break;
                
            case R.id.add:
                add();
                break;
        }
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
        if (id == PROGRESS_ID_SAVE) {
            mProgress = new ProgressDialog(this);
            mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgress.setMessage(getText(R.string.saving));
            return mProgress;
        }
        return super.onCreateDialog(id);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH ||
            event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            query();
            return true;
        }
        return false;
    }

    /**
     * Query weather
     * 
     * @return
     */
    private int query() {
        if (!Util.isNetworkAvail(this)) {
            Util.showToast(this, R.string.check_network);
            return C.ERROR;
        }
        
        final String cityName = mEditCity.getText().toString();
        if (cityName.length() == 0) {
            Util.showToast(this, R.string.enter_location);
            return C.ERROR;
        }
        
        Util.hideSoftkeyboard(this, mEditCity);
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        enableQuery(false);
                        enableAdd(false);
                        mCityLayout.setVisibility(View.GONE);
                        mQueryProgress.setVisibility(View.VISIBLE);
                    }
                });
                WeatherInfo city = new WeatherInfo(cityName);
                mApplication.getEngine().getWeatherDataForAdd(mGeocoder, city, mHandler);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        enableQuery(true);
                        mCityLayout.setVisibility(View.VISIBLE);
                        mQueryProgress.setVisibility(View.GONE);
                        enableAdd(true);
                    }
                });
            }
        });
        thread.start();        
        
        return C.SUCCESS;
    }
    
    /**
     * Add to user database
     * 
     * @return
     */
    private int add() {
        final String path = UserDatabaseHelper.getDatabasePath();
        if (path == null) {
            Util.showToast(this, R.string.check_sdcard);
            return C.ERROR;
        }
        
        if (UserDatabaseHelper.checkOrCreateDir() == C.ERROR) {
            Util.showToast(this, "Failed to check directory");
            return C.ERROR;
        }
        
        showDialog(PROGRESS_ID_SAVE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                UserDatabaseHelper dbHelper = new UserDatabaseHelper(AddLocationActivity.this, path);
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                
                ContentValues values = new ContentValues();
                values.put(UserDatabaseHelper.ITEM_CITY_NAME, mWeatherInfo.cityName);
                values.put(UserDatabaseHelper.ITEM_LATITUDE, mWeatherInfo.latitude);
                values.put(UserDatabaseHelper.ITEM_LONGITUDE, mWeatherInfo.longitude);
                values.put(UserDatabaseHelper.ITEM_ALTITUDE, mWeatherInfo.altitude);
                
                long ret = db.insert(UserDatabaseHelper.TABLE_NAME, null, values);
                db.close();
                mApplication.setDatabaseModifiedTime(UserDatabaseHelper.getModifiedTime());

                if (ret == -1) {
                    mHandler.sendEmptyMessage(Engine.MSG_ERROR);
                }
                else {
                    mHandler.sendEmptyMessage(Engine.MSG_SAVE_DONE);
                }
            }
        }).start();
        
        return C.SUCCESS;
    }
    
    /**
     * Enable or disable query button
     * 
     * @param enable
     */
    private void enableQuery(boolean enable) {
        mButtonQuery.setEnabled(enable);
    }
    
    /**
     * Enable or disable add button
     * 
     * @param enable
     */
    private void enableAdd(boolean enable) {
        mButtonAdd.setEnabled(enable);
    }
    
    /**
     * Receive the result of a query weather
     */
    class NetworkHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Engine.MSG_DONE:
//                    Util.showToast(AddLocationActivity.this, "Done");
                    mCityLayout.setVisibility(View.VISIBLE);
                    mWeatherInfo = (WeatherInfo)msg.obj;
                    mCityName.setText(mWeatherInfo.cityName);
                    mIcon.setImageResource(WeatherInfo.getIconByWeatherCode(mWeatherInfo.weatherCode));
                    mCondition.setText(mWeatherInfo.condition);
                    mCode.setText(mWeatherInfo.latitude + ", " + mWeatherInfo.longitude);
                    break;
                    
                case Engine.MSG_ERROR:
                    if (mProgress != null) {
                        mProgress.dismiss();
                    }
                    Util.showToast(AddLocationActivity.this, R.string.error);
                    break;
                    
                case Engine.MSG_SAVE_DONE:
                    if (mProgress != null) {
                        mProgress.dismiss();
                    }
                    ((RuleTheRainApplication)getApplication()).loadCityList();
                    break;
            }
        }
    }
}
